"use client"

import type React from "react"
import { createContext, useContext, useState, useEffect } from "react"
import { useToast } from "@/components/ui/use-toast"
import { userConfig } from "./config"
import { getUserProgress, getUserWrongAnswers } from "./api-service"

type User = {
  id: string
  name: string
} | null

type UserContextType = {
  user: User
  login: () => void
  logout: () => void
  isLoading: boolean
}

const UserContext = createContext<UserContextType | undefined>(undefined)

export function UserProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User>(null)
  const [isLoading, setIsLoading] = useState(true)
  const { toast } = useToast()

  // 检查本地存储中是否有用户信息
  useEffect(() => {
    const loadUserData = async () => {
      setIsLoading(true)
      const storedUser = localStorage.getItem(userConfig.userKey)

      if (storedUser) {
        const parsedUser = JSON.parse(storedUser)
        setUser(parsedUser)

        try {
          // 尝试从后端获取用户数据
          await getUserProgress(parsedUser.id)
          await getUserWrongAnswers(parsedUser.id)
        } catch (error) {
          console.error("Error loading user data from backend:", error)
          // 如果后端获取失败，我们仍然使用本地数据
        }
      }

      setIsLoading(false)
    }

    loadUserData()
  }, [])

  // 模拟登录功能
  const login = () => {
    const newUser = {
      id: "user_" + Math.random().toString(36).substr(2, 9),
      name: "学生用户",
    }
    setUser(newUser)
    localStorage.setItem(userConfig.userKey, JSON.stringify(newUser))
    localStorage.setItem(userConfig.userIdKey, newUser.id)

    toast({
      title: "登录成功",
      description: `欢迎回来，${newUser.name}！`,
    })
  }

  // 登出功能
  const logout = () => {
    setUser(null)
    localStorage.removeItem(userConfig.userKey)
    localStorage.removeItem(userConfig.userIdKey)
    localStorage.removeItem(userConfig.wrongAnswersKey)
    localStorage.removeItem(userConfig.progressKey)
    localStorage.removeItem(userConfig.writingAnswersKey)

    toast({
      title: "已退出登录",
      description: "您已成功退出系统",
    })
  }

  return <UserContext.Provider value={{ user, login, logout, isLoading }}>{children}</UserContext.Provider>
}

export function useUser() {
  const context = useContext(UserContext)
  if (context === undefined) {
    throw new Error("useUser must be used within a UserProvider")
  }
  return context
}
